package com.lagou.miaosha.rocketmq.service.impl;

import com.lagou.miaosha.rocketmq.mapper.StockMapper;
import com.lagou.miaosha.rocketmq.pojo.Stock;
import com.lagou.miaosha.rocketmq.service.IStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * @Description TODO
 * @Classname IStockServiceImpl
 * @Date 2021/8/1 17:41
 * @Author ch'ien
 */
@Service
public class IStockServiceImpl implements IStockService {

    private static final String GOODS_PREFIX = "GOODS";

    @Autowired
    private RedisTemplate<String, Integer> redisTemplate;

    @Autowired
    private StockMapper stockMapper;

    @Override
    public Integer getStockCount(Integer gid) {

        Integer count = redisTemplate.opsForValue().get(GOODS_PREFIX + ":" + gid);

        return Optional.ofNullable(count).orElse(0);
    }

    @Override
    public Stock getOneByGid(Integer gid) {
        return stockMapper.getOneByGid(gid);
    }

    @Override
    public void decrement(Integer gid) {
        redisTemplate.opsForValue().decrement(GOODS_PREFIX + ":" + gid);

    }
    @Override
    public void increment(Integer gid) {
        redisTemplate.opsForValue().increment(GOODS_PREFIX + ":" + gid);
    }

    @Override
    public void decrementStock(Integer gid) {
        stockMapper.decrementStock(gid);
    }

    @Override
    public void incrementStock(Integer gid) {
        stockMapper.incrementStock(gid);
    }

    @Override
    public List<Stock> getList() {
        List<Stock> list = stockMapper.getList();
        Iterator<Stock> iterator = list.iterator();
        while (iterator.hasNext()){
            Stock next = iterator.next();
            Integer integer = redisTemplate.opsForValue().get(GOODS_PREFIX + ":" + next.getGoodsId());
            if (integer == null || integer<=0){
                iterator.remove();
            }
        }
        return list;
    }


    @PostConstruct
    public void init(){
        List<Stock> list = stockMapper.getList();
        for (Stock stock : list) {

            redisTemplate.opsForValue().set(GOODS_PREFIX + ":" + stock.getGoodsId(),
                    stock.getNum());

        }
    }
}
